#include<at89c51ed2.h>
#include<mcs51reg.h>

#include<stdio.h>

#include "io.h"

/**************************************************************************/
#define SPI_SS P1_3 /*SPI Slave Select (can be used with 74LS138 to operate two SPI slaves)*/



/**************************************************************************/

void Master_spi_init(int device)__critical/*1 for rssi chip 2 for memmory chip*/
{
	if(device==1)
	{
	SPCON=0x31;	/*Master Mode SSDIS=1 MSTR=1, Baud Rate: Fclk/4 (X1 Mode),CPOL=0,CPHA=0 as device samples data on
				rising edge of SCK*/
	SPCON|=0x40; /*Enable Master SPEN=1, spi initiated*/
	}
	if(device==2)
	{
	SPCON=0x34;	/*Master Mode SSDIS=1 MSTR=1, Baud Rate: Fclk/2 (X1 Mode),CPOL=0,CPHA=0 as device samples data on
				rising edge of SCK*/
	SPCON|=0x40; /*Enable Master SPEN=1, spi initiated*/
	}
	
	
}
//
void spiChipSelectON(int device)
{
//	Master_spi_init(device);
if(device==1)
{
	P1_3=0;
}
if(device==2)
{
	P1_4=0;	
	
}

}


void spiChipSelectOFF(int device)
{
//	Master_spi_init(device);
if(device==1)
{
	P1_3=1;
}
if(device==2)
{
	P1_4=1;	

}

}

	

void spi_dataSend(int txData)__critical
{
	int rxDummy;
	volatile int dataStatus; /*force control to check SPIF each time*/
	
	
	
	
	SPDAT=txData;		/*put data in SPDAT for spi transfer*/

	dataStatus=SPSTA;
	dataStatus&=0x80;
	
	while(dataStatus==0)
	{
		dataStatus=SPSTA;
		dataStatus&=0x80;
	}
	

	rxDummy=SPDAT;		/*dummy SPDAT read for clearing SPIF*/

	
}
 

int spi_dataRead(int reg_addr,int device)__critical
{
	int rxData;
	int txDummy;
	int ack;
	volatile int dataStatus; /*force control to check SPIF each time*/
	int i;
	
	ack=1;
	txDummy=0;
	i=0; //counter for multibyte read
	 
	spiChipSelectON(device);  /*slave select*/

	/*send register address*/
	SPDAT=reg_addr;		/*put data in SPDAT for spi transfer*/
	dataStatus=SPSTA;
	dataStatus&=0x80;
	
	while(dataStatus==0)
	{
		dataStatus=SPSTA;
		dataStatus&=0x80;
	}
	
	/*end of transmitting register address*/
  /****************************************************************/	
	
	
	SPDAT=txDummy;		/*put data in SPDAT for spi transfer*/
	
	
	dataStatus=SPSTA;
	dataStatus&=0x80;
	
	while(dataStatus==0)
	{
		dataStatus=SPSTA;
		dataStatus&=0x80;
	}
	
	/**single byte for rssi, multibyte for memory*/

	
	rxData=SPDAT; /*transfer received data*/
	


	
	spiChipSelectOFF(device);  /*slave select*/


	

  
	   	return rxData;		/*return data*/
}
	
	
